class Solution:
    def shipWithinDays(self, weights: list, D: int) -> int:
        def isValid(capacity, weights, D):
            days = 0
            cur = 0
            for i in range(len(weights)):
                cur += weights[i]
                if cur > capacity:
                    days += 1
                    cur = weights[i]
            days += 1
            return days <= D

        start = max(weights)
        end = sum(weights)

        while start + 1 < end:
            mid = (start + end) // 2
            if isValid(mid, weights, D):
                end = mid
            else:
                start = mid
        if isValid(start, weights, D):
            return start
        if isValid(end, weights, D):
            return end

        return -1
